import List from '@/model/List'
// import Links from '@/model/Links'
import Ads from '@/model/Ads'
import User from '@/model/User'
import qs from 'qs'
import fs from 'fs'
import { v4 as uuid } from 'uuid'
import moment from 'moment'
import config from '@/config'
// import { dirExists } from '@/common/Utils'
import mkdir from 'make-dir'
import { getJWTPayload } from '../common/Utils'
import { checkCode, rename } from '../common/Utils'
import Collect from '@/model/collect'

class ContentController {
  //文章列表
  async getList(ctx) {
    const body = qs.parse(ctx.request.query)
    const sort = body.sort ? body.sort : 'created'
    const page = body.page ? parseInt(body.page) : '0'
    const limit = body.limit ? parseInt(body.limit) : 20
    const options = {}
    if (typeof body.catalog !== 'undefined' && body.catalog !== '') {
      options.catalog = body.catalog
    }
    if (typeof body.isTop !== 'undefined') {
      options.isTop = body.isTop
    }
    if (typeof body.status !== 'undefined' && body.status !== '') {
      options.isEnd = body.status
    }
    if (typeof body.tag !== 'undefined' && body.tag !== '') {
      options.tags = { $elemMatch: { name: body.tag } }
    }
    const result = await List.getList(options, sort, page, limit)
    ctx.body = {
      code: 200,
      data: result,
      msg: '获取文章列表成功',
    }
  }
  //新增发帖
  async addArticle(ctx) {
    const { body } = ctx.request
    let obj = await getJWTPayload(ctx.header.authorization)
    let sid = body.sid
    let code = body.code
    let msg = {}
    //校验验证码
    let result = await checkCode(sid, code)
    //查询user表的积分数
    if (result) {
      let user = await User.findOne({ _id: obj._id })
      let created = moment().format('YYYY-MM-DD HH:mm:ss')
      if (user.favs >= body.fav) {
        let favs = user.favs - body.fav
        await User.updateOne(
          {
            _id: obj._id,
          },
          {
            favs: favs,
          }
        )
        let list = new List({
          catalog: body.catalog,
          title: body.title,
          fav: body.fav, //
          content: body.content,
          created: created,
          uid: obj._id,
        })

        // let user = new User({
        //   favs: favs,
        // })
        // user.updateOne(
        //   {
        //     _id: obj._id,
        //   },
        //   {
        //     $inc: { favs: favs },
        //   }
        // )
        let result = await list.save()
        ctx.body = {
          code: 200,
          msg: '发帖成功',
        }
      } else {
        ctx.body = {
          code: 500,
          msg: '积分不足无法正常发帖',
        }
      }
    } else {
      // veevalidate 显示的错误
      ctx.body = {
        code: 401,
        msg: '图片验证码不正确,请检查!',
      }
    }
  }

  async editArticle(ctx) {
    const { body } = ctx.request
    // console.log('TCL:', body)
    let sid = body.sid
    let code = body.code
    let tid = body.tid
    let msg = {}
    let result = await checkCode(sid, code)
    //查询user表的积分数
    if (result) {
      if (ctx.header.authorization !== 'undefined') {
        let obj = await getJWTPayload(ctx.header.authorization)
        const list = await List.findOne({ _id: tid })
        if (list.uid === obj._id) {
          //修改帖子
          let list = await List.updateOne(
            { _id: tid },
            {
              title: body.title,
              content: body.content,
            }
          )
          if (list.matchedCount === 1) {
            ctx.body = {
              code: 200,
              msg: '修改帖子成功',
              data: list,
            }
          }
        } else {
          ctx.body = {
            code: 404,
            msg: '该帖子非你创建无法编辑',
          }
        }
      } else {
        ctx.body = {
          code: 500,
          msg: '用户未登录或未授权',
        }
      }
    } else {
      ctx.body = {
        code: 401,
        msg: '验证码错误请重试',
      }
    }
  }
  async setCollect(ctx) {
    const body = qs.parse(ctx.request.query)
    //同一个人只允许收藏一次再点击删除
    const res = await Collect.findOne({ uid: body.uid, tid: body.tid })
    if (!res && body.isFav === '1') {
      const collect = new Collect({
        uid: body.uid,
        tid: body.tid,
        title: body.title,
        created: moment().format('YYYY-MM-DD'),
      })
      const result = collect.save()
      ctx.body = {
        code: 200,
        msg: '收藏成功',
      }
    } else if (res && body.isFav === '0') {
      const result1 = await Collect.deleteOne({
        uid: body.uid,
        tid: body.tid,
        title: body.title,
      })
      ctx.body = {
        code: 200,
        msg: '取消收藏成功',
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '取消收藏失败',
      }
    }
  }
  //置顶
  async addTop(ctx) {
    const body = qs.parse(ctx.request.query)
    // console.log(body);
    const tid = body.tid
    const uid = body.uid
    const user = await User.findByID(uid)
    for (let key in user.roles) {
      // console.log(user.roles[key])
      if (user.roles[key] !== 'admin') {
        ctx.body = {
          code: 500,
          msg: '置顶失败',
        }
        return
      } else {
        const list = await List.updateOne(
          { _id: tid },

          {
            $set: {
              isTop: 1,
            },
          }
        )
        if (list.matchedCount === 1) {
          ctx.body = {
            code: 200,
            msg: '置顶成功',
          }
        }
      }
    }
  }
  //加精
  async addTags(ctx) {
    const body = qs.parse(ctx.request.query)
    const tid = body.tid
    const uid = body.uid
    const user = await User.findByID(uid)
    for (let key in user.roles) {
      if (user.roles[key] !== 'admin') {
        ctx.body = {
          code: 500,
          msg: '加精失败',
        }
        return
      } else {
        const list = await List.updateOne(
          { _id: tid },

          {
            $set: {
              tags: { name: '精华', class: 'layui-bg-red' },
            },
          }
        )
        if (list.matchedCount === 1) {
          ctx.body = {
            code: 200,
            msg: '置顶成功',
          }
        }
      }
    }
  }
  //友联
  async getLinks(ctx) {
    const result = await Links.find({ type: 'links' })
    ctx.body = {
      code: 200,
      data: result,
    }
  }
  async getTips(ctx) {
    const result = await Links.find({ type: 'tips' })
    ctx.body = {
      code: 200,
      data: result,
    }
  }
  //热议
  async getHotWeek(ctx) {
    const result = await List.getHotWeek({ type: 'tips' })
    ctx.body = {
      code: 200,
      data: result,
    }
  }
  //广告位
  async getadver(ctx) {
    const result = await Ads.find({})
    ctx.body = {
      code: 200,
      data: result,
    }
  }
  //图片上传
  async uploadImg(ctx) {
    const file = ctx.request.files.file
    // console.log(file);
    const filname = ctx.request.files.file.name
    //图片名称 格式 存储位置 返回前台可读取得路径
    const partfile = /\.([0-9a-z]+)(?:[\?#]|$)/i
    const ext = filname.match(partfile)
    // const ext = file.name.split('.').pop() //文件后缀
    // console.log(ext);
    // const dir = `../../public/${moment().format('YYYYMMDD')}`
    //测试方法1
    // const dir = `${config.uploadPath}/path/path2/${moment().format('YYYYMMDD')}`
    // console.log(dir);
    //判断路径是否存在 不存在就创建
    // await dirExists(dir)
    const dir = `${config.uploadPath}/tx/${moment().format('YYYYMMDD')}`
    await mkdir(dir)
    //存储文件到指定的数据
    //给文件一个唯一的名称
    const picname = uuid()
    const destPath = `${dir}/${picname}${ext[0]}`
    const reader = fs.ReadStream(file.path) //buffer默认64kb
    const upStream = fs.WriteStream(destPath)
    const filePath = `/tx/${moment().format('YYYYMMDD')}/${picname}${ext[0]}`

    //method1
    reader.pipe(upStream) //应付小文件
    //method2
    // const stat = fs.statSync(file.path)
    // console.log(stat);
    // let totalLength = 0
    // reader.on('data',(chunk)=>{
    //     totalLength +=chunk.length
    //     if(upStream.write(chunk) === false){
    //         reader.pause()
    //     }
    // })

    // reader.on('drain',()=>{
    //     reader.resunme()
    // })

    // reader.on('end',()=>{
    //     upStream.end()
    // })

    ctx.body = {
      code: 200,
      msg: '图片上传成功',
      data: filePath,
    }
  }
  //获取具体文章 可以传用户id
  async getPostDetail(ctx) {
    // let params = ctx.query
    let params = qs.parse(ctx.request.query)
    if (!params.tid) {
      ctx.body = {
        code: 500,
        msg: '文章id为空',
      }
    }
    let post = await List.findByUid({ _id: params.tid })
    let obj = {}
    /////////
    //登录情况出现undfind
    let isFav = 0
    if (typeof ctx.header.authorization !== 'undefined') {
      obj = await getJWTPayload(ctx.header.authorization)
    }
    if (typeof obj._id !== 'undefined') {
      let collect = await Collect.findOne({ tid: params.tid, uid: obj._id })
      if (collect !== null) {
        if (collect[0] !== '') {
          if (collect.uid === obj._id) {
            isFav = 1
          }
        }
      }
    }
    let list = post.toJSON()
    list.isFav = isFav
    const result = rename(list, 'uid', 'user')
    const result1 = await List.updateOne(
      { _id: params.tid },
      {
        $inc: {
          reads: 1,
        },
      }
    )
    if (post._id && result1.matchedCount === 1) {
      ctx.body = {
        code: 200,
        data: list,
        msg: '查询文章成功',
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '查询文章失败',
      }
    }
    ///////////
    // 更新文章阅读数
    // const result1 = await List.updateOne(
    //   { _id: params.tid },
    //   {
    //     $inc: {
    //       reads: 1,
    //     },
    //   }
    // )
    // if (post._id && result1.matchedCount === 1) {
    //   ctx.body = {
    //     code: 200,
    //     data: post,
    //     msg: '查询文章成功',
    //   }
    // } else {
    //   ctx.body = {
    //     code: 500,
    //     msg: '查询文章失败',
    //   }
    // }
  }
}

export default new ContentController()
